package com.alm.token.ui.viewpagefragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.R;
import com.alm.token.apinew.AllApi;
import com.alm.token.base.BaseAdapter;
import com.alm.token.base.BaseViewPageFragment;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.activity.ActivityListActivity;
import com.alm.token.ui.activity.BlockWalletLoginActivity;
import com.alm.token.ui.activity.BuyEggPartnerActivity;
import com.alm.token.ui.activity.BuyHMioIndexActivity;
import com.alm.token.ui.activity.BuyMioEXPartnerActivity;
import com.alm.token.ui.activity.BuyMioOPRActivity;
import com.alm.token.ui.activity.CandyActivity;
import com.alm.token.ui.activity.HMioMapActivity;
import com.alm.token.ui.activity.QuantitativeSplashActivity;
import com.alm.token.ui.activity.StakingSplashActivity;
import com.alm.token.ui.activity.SuperColorEggActivity;
import com.alm.token.ui.activity.TransformActivity;
import com.alm.token.ui.activity.TurnOutBiTBActivity;
import com.alm.token.ui.activity.VipApplyActivity;
import com.alm.token.ui.data.bean.FindMoreData;
import com.alm.token.ui.data.bean.FindMoreNewData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.PayPswView;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.StringUtils;
import com.alm.token.utils.Utils;
import com.alm.token.widget.CustomTabLayout;
import com.alm.token.widget.bannerview.BGABanner;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import retrofit2.Retrofit;
//import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

//import rx.android.schedulers.AndroidSchedulers;

public class FindMorePageFrag extends BaseViewPageFragment implements PayPswView<FindMoreNewData> {

    //    @BindView(R.id.bga_terminalDetail)
    BGABanner bgaBanner;
    @BindView(R.id.tab)
    CustomTabLayout tab;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;

    private View bannerView;
    Retrofit retrofit;
    //    ApiService service;
    AllApi apiStores;
    private String id = "0", flag = "down", limit = "10";
    private int top_id = 0;
    private int bottom_id = 0;
    private RefreshLoadMoreManager<FindMoreNewData.DataBean.ApplicationBean> manager;

    private List<FindMoreData.ListBean.LivesBean> dataBeans = new ArrayList<>();
    private List<FindMoreNewData.DataBean.ApplicationBean> applicationBeans = new ArrayList<>();
    private List<FindMoreNewData.DataBean.ApplicationBean> footprint = new ArrayList<>();
    private List<String> pictureUrls = new ArrayList<>();
    //    NoScrollViewPager viewPager;
    private String date;

    public static FindMorePageFrag newInstance() {
        FindMorePageFrag fragment = new FindMorePageFrag();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.viewpage_fragment_findmore;
    }

    @Override
    protected void initVariables() {
        bannerView = getActivity().getLayoutInflater().inflate(R.layout.viewpage_fragment_findmore_top, null);
        bgaBanner = bannerView.findViewById(R.id.bga_terminalDetail);

        bgaBanner.setAdapter(new BGABanner.Adapter() {
            @Override
            public void fillBannerItem(BGABanner banner, View view, Object model, int position) {
                ImageView imageView = (ImageView) view;
//                ImageLoaderUtils.display(imageView, imagesBanner.get(position));
//                //TODO  临时写成网络加载错误时，加载本地的3张图片
//                Glide.with(imageView.getContext())
//                        .load(DataCenter.BASE_URL_FILE + imagesBanner.get(position))
//                        .diskCacheStrategy(DiskCacheStrategy.ALL)
//                        .centerCrop()
//                        .error(imagesForNoData.get(position))
//                        .crossFade(1000).into(imageView);


                //设置图片圆角角度
                RequestOptions myOptions = RequestOptions.bitmapTransform(new MultiTransformation(
                        new CenterCrop(),
                        new RoundedCorners(20),
                        new RoundedCornersTransformation(Utils.dp2px(getActivity(), 8), 2)));

                String img_url = (String) model;
                GlideApp.with(imageView.getContext()).load(ConStant.HOST + img_url).apply(myOptions).error(R.mipmap.img_haibao).into(imageView);

//                Glide.with(imageView.getContext())
//                        .load(img_url)
//                        .into(imageView);
            }
        });
//        retrofit = new Retrofit.Builder()
//                // 设置解析转换工厂
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                // 设置请求的域名
////                .baseUrl("http://api.coindog.com")
//                .baseUrl(ConStant.HOST)
//                .build();
//        apiStores = retrofit.create(AllApi.class);
    }

    private void initTab() {
//        String[] tabNames = {"全部", "链上异动", "币种", "交易所", "动态"};
//        List<Fragment> fragmentList = new ArrayList<>();
//        fragmentList.add(new Fragment());
//        fragmentList.add(new Fragment());
//        fragmentList.add(new Fragment());
//        fragmentList.add(new Fragment());
//        fragmentList.add(new Fragment());
//
//        tab.setItemLayout(R.layout.item_message_tab);
//        tab.setTabNames(tabNames);
//        tab.notifyChange();
//        tab.setViewPager(viewPager);
//
//
//        viewPager.setAdapter(new ItemTitlePagerAdapter(getChildFragmentManager(),
//                fragmentList, tabNames));
//        viewPager.setOffscreenPageLimit(5);
//        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                tab.setSelectedView(position);
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });

    }

    @Override
    protected void initViews(View view) {

//        initTab();
        initManager();
        swipeRefreshLayout.setVisibility(View.GONE);
        tvClickreload.setOnClickListener(this);

    }

    private void initManager() {
        MessageAdapter adapter = new MessageAdapter(getActivity());
        LinearLayoutManager llm = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        manager = new RefreshLoadMoreManager.Builder(getActivity())
                .setAdapter(adapter)
                .setLayoutManager(llm)//new GridLayoutManager(getActivity(), 3)
                .setRecyclerView(recyclerView)
                .setSwipeRefreshLayout(swipeRefreshLayout)
                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
//                        swipeRefreshLayout.setRefreshing(false);
//                        //    默认值 : id=0&flag=down，获取最新的 {limit} 条快讯记录
//                        //    使用 : id=100&flag=down, 获取小于id 100 的 {limit} 条快讯记录，适用于获取历史快讯
//                        //    使用 : id=200&flag=up, 获取大于id 200 的 {limit} 条快讯记录，适用于获取最新快讯（注意，
//
//                        id = top_id + "";
//                        flag = "up";
                        loadData();
                    }
                })
                .setOpenLoadMore(false)
//                .setOnLoadMoreListener(new RefreshLoadMoreManager.OnLoadMoreListener() {
//                    @Override
//                    public void onLoadMore() {
////                        manager.getAdapter().loadMoreEnd(true);
////                        manager.getAdapter().loadMoreFail();
////                        id = bottom_id + "";
////                        flag = "down";
//                        loadData();
//
//                    }
//                })
                .build();
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (ishavePaypsw == -1) {
                    showToast(getString(R.string.common_loading));
                    preenter.getHavePayPwd();
                    return;
                } else if (ishavePaypsw == 0) {
                    ishavePaypsw = 1;
                    jumpToLoginAct(4);
                    return;
                }
                if (EmptyUtils.isNotEmpty(applicationBeans) && position < applicationBeans.size()) {

                    int beansId = applicationBeans.get(position).getId();
                    if (beansId == 5) {
                        //量化
                        startActivity(QuantitativeSplashActivity.class);
                    } else if (beansId == 6) {
                        //超级彩蛋
                        startActivity(SuperColorEggActivity.class);
                    } else if (beansId == -1) {
                        //彩蛋合伙人
                        startActivity(BuyEggPartnerActivity.class);
                    } else if (beansId == 12) {
                        //VIP
                        startActivity(VipApplyActivity.class);
                    } else if (beansId == 7) {
                        //币币兑换 闪兑
                        startActivity(TransformActivity.class);
                    } else if (beansId == 11) {
                        //币币互转 M-Pay
//                        startActivity(TurnOutBiTB_shoukuanren_Activity.class);
                        startActivity(TurnOutBiTBActivity.class);
                    } else if (beansId == 10) {
                        //糖果
                        startActivity(CandyActivity.class);
                    } else if (beansId == 13) {
                        //活动
                        startActivity(ActivityListActivity.class);
                    } else if (beansId == 14) {
                        //MIOex
                        startActivity(BuyMioEXPartnerActivity.class);
                    } else if (beansId == 15) {
                        //MIOex
                        startActivity(BuyMioOPRActivity.class);
                    } else if (beansId == 16) {
                        //HMIO 抢购
                        startActivity(BuyHMioIndexActivity.class);
                    } else if (beansId == -2) {
                        //全球go
                        showToast(getString(R.string.common_opentip1));
                    } else if (beansId == 2) {
                        //全球go
//                        showToast(getString(R.string.common_opentip1));
                        startActivity(StakingSplashActivity.class);
                    }else if (beansId == 1) {
                        //全球go
//                        showToast(getString(R.string.common_opentip1));
                        startActivity(HMioMapActivity.class);
                    }
                }
            }
        });
        adapter.addHeaderView(bannerView);
    }


    @Override
    protected void loadData() {
        showWaitDialog();
        preenter.getFindMoreDataNew();
        preenter.getHavePayPwd();

//        apiStores.getFindMoreData(id + "", flag + "", limit + "")
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new BaseObserver<FindMoreData>() {
//                    @Override
//                    protected void onSuccees(FindMoreData findMoreData) throws Exception {
//                        hideWaitDialog();
//                        //请求成功
//                        if (findMoreData.getCount() != 0 && findMoreData.getList() != null && findMoreData.getList().size() != 0) {
//                            if (top_id == 0) {//第一次
//                                top_id = findMoreData.getTop_id();
//                                bottom_id = findMoreData.getBottom_id();
//                                for (int i1 = 0; i1 < findMoreData.getList().size(); i1++) {
//                                    dataBeans.addAll(findMoreData.getList().get(i1).getLives());
//                                    if (dataBeans != null && dataBeans.size() != 0) {
//                                        for (int i = 0; i < dataBeans.size(); i++) {
//                                            dataBeans.get(i).setLayoutId(MessageAdapter.LAYOUT_ID);
//                                            dataBeans.get(i).setDate(findMoreData.getList().get(i1).getDate());
//                                        }
//                                    }
//                                }
//                            } else if (top_id < findMoreData.getTop_id()) {//刷新最新的数据 可能会重复
//
//                                for (int i1 = 0; i1 < findMoreData.getList().size(); i1++) {
//                                    List<FindMoreData.ListBean.LivesBean> beans = new ArrayList<>();
//                                    beans.addAll(findMoreData.getList().get(i1).getLives());
//                                    if (beans != null && beans.size() != 0) {
//                                        for (int i = beans.size() - 1; i >= 0; i--) {
//                                            beans.get(i).setLayoutId(MessageAdapter.LAYOUT_ID);
//                                            beans.get(i).setDate(findMoreData.getList().get(i1).getDate());
//                                            if (!dataBeans.contains(beans.get(i))) {
//                                                dataBeans.add(0, beans.get(i));
//                                            } else {
////                                                showToast("true");
//                                            }
//                                        }
//                                    }
//                                }
//
//                                top_id = findMoreData.getTop_id();
//                            } else if (bottom_id > findMoreData.getBottom_id()) {//加载的历史书籍
//                                for (int i1 = 0; i1 < findMoreData.getList().size(); i1++) {
//                                    List<FindMoreData.ListBean.LivesBean> beans = new ArrayList<>();
//                                    beans.addAll(findMoreData.getList().get(i1).getLives());
//                                    if (beans != null && beans.size() != 0) {
//                                        for (int i = beans.size() - 1; i >= 0; i--) {
//                                            beans.get(i).setLayoutId(MessageAdapter.LAYOUT_ID);
//                                            beans.get(i).setDate(findMoreData.getList().get(i1).getDate());
//                                        }
//                                    }
//                                    dataBeans.addAll(beans);
//                                }
//                                bottom_id = findMoreData.getBottom_id();
//                            }
//                            if (dataBeans != null && dataBeans.size() > 0) {
//                                manager.setData(dataBeans);
//                                swipeRefreshLayout.setVisibility(View.VISIBLE);
//                                nodatashowBody.setVisibility(View.GONE);
//                            } else {
//                                swipeRefreshLayout.setVisibility(View.GONE);
//                                nodatashowBody.setVisibility(View.VISIBLE);
//                            }
//                        }
////                        if(t.isSuccess()){
////                            view.setContent("Hello---->"+t.getData().getName());
////                        }else {
////                            view.setContent("----->"+t.getMessage());
////                        }
//                    }
//
//                    @Override
//                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
////                        view.setContent("失败了----->"+e.getMessage());
//                        hideWaitDialog();
//                        showToast(e.toString());
//                        LogUtil.e( e.toString());
//                    }
//                });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_clickreload:
                loadData();
                break;
        }

    }

    @Override
    public void getData(FindMoreNewData findMoreNewData) {

        if (findMoreNewData.getStatus() == 0) {
            if (EmptyUtils.isNotEmpty(findMoreNewData) && EmptyUtils.isNotEmpty(findMoreNewData.getData())
                    && EmptyUtils.isNotEmpty(findMoreNewData.getData().getApplication())) {
                applicationBeans = findMoreNewData.getData().getApplication();
                footprint = findMoreNewData.getData().getFootprint();
//                pictureUrls = findMoreNewData.getData().getPictureUrl();
                pictureUrls.add("/static/images/cn-2.png");
                if (EmptyUtils.isNotEmpty(applicationBeans) || EmptyUtils.isNotEmpty(footprint)) {
                    if (applicationBeans != null && applicationBeans.size() > 0) {
                        applicationBeans.remove(null);
                        for (FindMoreNewData.DataBean.ApplicationBean applicationBean : applicationBeans) {
                            applicationBean.setLayoutId(MessageAdapter.LAYOUT_ID);
                        }
                        applicationBeans.get(0).setType11(1);
                    }
//                    if (footprint != null && footprint.size() > 0) {
//                        footprint.remove(null);
//                        for (FindMoreNewData.DataBean.ApplicationBean applicationBean : footprint) {
//                            applicationBean.setLayoutId(MessageAdapter.LAYOUT_ID);
//                        }
//                        footprint.get(0).setType(2);
//                        applicationBeans.addAll(footprint);
//                    }

                    manager.setData(applicationBeans);
                    swipeRefreshLayout.setVisibility(View.VISIBLE);
                    nodatashowBody.setVisibility(View.GONE);

                } else {
                    swipeRefreshLayout.setVisibility(View.GONE);
                    nodatashowBody.setVisibility(View.VISIBLE);
                }

                if (EmptyUtils.isNotEmpty(pictureUrls)) {
                    bgaBanner.setAutoPlayAble(true);
//                    pictureUrls.clear();
//                    for (String imgurl : findMoreNewData.getData().getPictureUrl()) {
//                        pictureUrls.add(ConStant.HOST + imgurl);
//                    }
                    bgaBanner.setData(pictureUrls, null);
                    swipeRefreshLayout.setVisibility(View.VISIBLE);
                    nodatashowBody.setVisibility(View.GONE);
                } else {
                    bgaBanner.setVisibility(View.GONE);
                }
            }
        } else {
            showToast(findMoreNewData.getMsg());
        }

    }

    @Override
    public void getCode(FindMoreNewData findMoreNewData) {

    }

    int ishavePaypsw = -1;

    @Override
    public void getHavePayPwd(RegisterData isHavePayPwd) {
        //"data": 1, // 1 有 0 没有
        if (isHavePayPwd.getData().equalsIgnoreCase("0")) {
            ishavePaypsw = 0;
//            jumpToLoginAct(4);
        } else {
            ishavePaypsw = 1;
        }
    }

    @Override
    public void sendMailCode(RegisterData registerData) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            getActivity().sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            getActivity().finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(getActivity(),PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType", PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            getActivity().finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }


    public class MessageAdapter extends BaseAdapter<FindMoreNewData.DataBean.ApplicationBean> {

        public static final int LAYOUT_ID = R.layout.item_findmore;

        public MessageAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, FindMoreNewData.DataBean.ApplicationBean item, int itemType) {
//            helper.getAdapterPosition()
            helper.setGone(R.id.tv_topshow, item.getType11() != 0 ? true : false);
            helper.setText(R.id.tv_topshow, getResources().getString(item.getType11() == 1 ? R.string.findmore_hint_fire : R.string.currency_hint1_warn));
            helper.setText(R.id.tv_itemname, item.getName());

            FindMoreNewData.DataBean.ApplicationBean.SubTitlesBean subTitles = item.getSubTitles();
            LinearLayout linearLayout = helper.getView(R.id.ly_firebody);
            for (int i = 0; i < linearLayout.getChildCount(); i++) {
                linearLayout.getChildAt(i).setVisibility(i < subTitles.getKey4() ? View.VISIBLE : View.GONE);
            }

//            if (helper.getAdapterPosition() == 1) {
//                linearLayout.getChildAt(linearLayout.getChildCount() - 1).setVisibility(View.VISIBLE);
//            } else if (helper.getAdapterPosition() <= 3) {
//                linearLayout.getChildAt(linearLayout.getChildCount() - 1).setVisibility(View.GONE);
//            }

            helper.setText(R.id.tv_key1item, StringUtils.nullToStr(subTitles.getKey1()));
            helper.setText(R.id.tv_key2item, StringUtils.nullToStr(subTitles.getKey2()));
            helper.setText(R.id.tv_key3item, StringUtils.nullToStr(subTitles.getKey3()));
            helper.setText(R.id.tv_key5item, StringUtils.nullToStr(subTitles.getKey5()));
            helper.setText(R.id.tv_key6item, StringUtils.nullToStr(subTitles.getKey6()));

//            helper.setText(R.id.tv_itemdec, getString(item.getId() == 16 ? R.string.findmore_hint_hmio
//                    : item.getId() == 5 ? R.string.findmore_hint_ago
//                    : item.getId() == 2 ? R.string.findmore_hint_stk
//                    : item.getId() == 7 ? R.string.findmore_hint_bzhuan
//                    : item.getId() == 11 ? R.string.findmore_hint_mpay
//                    : item.getId() == 10 ? R.string.findmore_hint_candy
//                    : item.getId() == 12 ? R.string.findmore_hint_vip
//                    : item.getId() == 14 ? R.string.findmore_hint_mioex
//                    : item.getId() == 13 ? R.string.findmore_hint_activity : R.string.findmore_hint_nul
//            ));
            ImageView imageView = helper.getView(R.id.img_itemicon);
            GlideApp.with(imageView.getContext()).load(ConStant.HOST + item.getIconurl()).error(R.drawable.gonggao).into(imageView);
        }

    }

//    public class MessageAdapter extends BaseAdapter<FindMoreData.ListBean.LivesBean> {
//
//        public static final int LAYOUT_ID = R.layout.item_findmorelist_base;
//
//        public MessageAdapter(@NonNull Context context) {
//            super(context);
//        }
//
//        @Override
//        protected void convert(BaseViewHolder helper, FindMoreData.ListBean.LivesBean item, int itemType) {
//
//            TextView textView = helper.getView(R.id.tv_title);
////            textView.setMaxLines(4);
////            textView.setTextSize(12);
////            String adress = item.getToken() != null && !item.getToken().isEmpty() ? item.getToken(): " ";
////            if(adress!=null&&adress.length()>45){
////                adress=adress.substring(0, 41);
////            }
//            textView.setText(item.getContent());
//            helper.setText(R.id.tv_measge, "" + item.getContent());
//
////            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
////            formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
////            String hms = formatter.format(item.getCreated_at());
//
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd    HH:mm:ss");
//            Long time = Long.parseLong(item.getCreated_at() + "");
//            String format = simpleDateFormat.format(time * 1000);
//
////            helper.setText(R.id.tv_date, "" + item.getDate() + " " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(item.getCreated_at() + "")).split(" ")[1]);
//            helper.setText(R.id.tv_date, "" + format);
//
//        }
//
//    }
}
